package com.tianji.learning.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.tianji.common.utils.DateUtils;
import com.tianji.learning.domain.po.PointsRecord;
import com.tianji.learning.enums.PointsRecordType;
import com.tianji.learning.mapper.PointsRecordMapper;
import com.tianji.learning.service.IPointsRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 * 学习积分记录，每个月底清零 服务实现类
 * </p>
 *
 * @author ltd
 * @since 2024-06-30
 */
@Service
public class PointsRecordServiceImpl extends ServiceImpl<PointsRecordMapper, PointsRecord> implements IPointsRecordService {

    @Override
    public void addPointsRecord(Long userId, int points, PointsRecordType type) {
        //判断积分是否有上线
        //获取积分上线的值
        int maxPoints = type.getMaxPoints();


        if (maxPoints>0){
            //获取当月当天的时间
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime dayStartTime = DateUtils.getDayStartTime(now);
            LocalDateTime dayEndTime = DateUtils.getDayEndTime(now);


            //查询今日积分获取数量，select  sum(points) as points from points_record where user_id=2
            // and   type=3 and create_time
            //    between '2024-07-01 00:00:00' and '2024-07-01 23:59:59'

            PointsRecord pointsRecord = this.query().select("sum(points) as points")
                    .eq("user_id", userId)
                    .eq("type", type)
                    .between("create_time", dayStartTime, dayEndTime).one();
            Integer theSumOfPoints = pointsRecord.getPoints();
            //判断是否超过每日上线
            if (theSumOfPoints>=maxPoints){
                return;
            }
            if (theSumOfPoints+points>maxPoints){
                points=maxPoints-theSumOfPoints;
            }

        }
        PointsRecord pointsRecord1=new PointsRecord();
        pointsRecord1.setPoints(points);
        pointsRecord1.setType(type.getValue());
        pointsRecord1.setUserId(userId);
           save(pointsRecord1);
    }
}
